import { defineStore } from 'pinia'
import { queryInfo, accountLogin,refresh } from "@/services/user";
import { LoginParamsType } from "@/model/LoginParamsType";
import router from '@/config/routes'
import { useRouterStore} from './router'
import { getToken, removeToken, setToken } from "@/utils/localToken";
import md5 from 'js-md5';
import settings from '@/config/settings';

export interface User {
	id: number;
	nickName: string;
	pic: string;
	Roles: string[];
}
export const useUserStore = defineStore('user', {
	state: () => {
		return {
			user: {
				id: 0,
				nickName: '',
				pic: '',
				Roles: []
			},
			loginStatus:false,
			expired:0,
			message:0,
		}
	},
	actions: {
		async login( params: LoginParamsType) {
			try {
				const res = await accountLogin(params);
				
				const { token,expired } = res;
				setToken(token || '');
				await asyncRouter();
				this.expired=expired
				return true
			} catch (error) {
				return false
			}
			
		
		},
		async logout() {
			try {
				await removeToken();
				return true;
			} catch (error) {
				return false;
			}

		},
		async info() {
			try {
				const res = await queryInfo();
				this.user=res;
				this.loginStatus=true;
				return true
			} catch (error) {
				this.loginStatus=false;
				return false
			}
			
		
		},
		async refreshToken() {
			let  params={
				token:await getToken(),
				sign:'',
				timestamp:0
			}
			let timestamp = Date.now();
			let Sign = md5(timestamp + settings.SecretKey + 'ererr')
			params.sign = Sign;
			params.timestamp = timestamp;
			const response= await refresh(params);
			setToken(response);
		},
		
	}
})
const asyncRouter = async () => {
	const store=useRouterStore()
	await store.LoadRouter();
	const asyncRouters = store.asyncRouters;
	
	if (asyncRouters) {
		asyncRouters.forEach(asyncRouter => {
			router.addRoute("root",asyncRouter)
		})
	}
}